﻿using System;
using System.Web.Mvc;
using JetBrains.Annotations;
using System.Linq;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Contrib.Chapters.Models;
using Contrib.Chapters.Services;
using System.Collections.Generic;
using Orchard.Localization;
using Contrib.Chapters.ViewModels;

namespace Contrib.Chapters.Drivers {
    [UsedImplicitly]
    public class TocWidgetPartDriver : ContentPartDriver<TocWidgetPart> {
        private readonly IChapterService _chapterService;

        public TocWidgetPartDriver(IChapterService chapterService) {
            _chapterService = chapterService;
            T = NullLocalizer.Instance;
        }

        protected override string Prefix { get { return "TocWidget"; } }
        public Localizer T { get; set; }

        protected override DriverResult Display(TocWidgetPart part, string displayType, dynamic shapeHelper) {
            var book = _chapterService.GetBook(part.BookPartRecord.ContentItemRecord.Id);
            var chapters = new List<ChapterPart>();
            if ( book != null ) {
                chapters.AddRange(_chapterService.GetChapters(book));
            }

            return ContentShape("Parts_Chapters_TableOfContent",
                () => shapeHelper.Parts_Chapters_TableOfContent(ContentPart: part, Chapters: chapters, Book: book));
        }

        protected override DriverResult Editor(TocWidgetPart part, dynamic shapeHelper) {
            return Editor(part, null, shapeHelper);
        }

        protected override DriverResult Editor(TocWidgetPart part, IUpdateModel updater, dynamic shapeHelper) {
            return ContentShape(
                "Parts_Chapters_TableOfContent_Edit",
                () => {
                    var model = new TocWidgetViewModel();

                    if (updater != null) {
                        var oldSelectedBookId = model.SelectedBookId;
                        updater.TryUpdateModel(model, Prefix, null, null);
                        if (oldSelectedBookId != model.SelectedBookId) {
                            part.BookPartRecord = _chapterService.GetBook(model.SelectedBookId).Record;
                        }
                    }

                    var books = _chapterService.GetBooks();

                    var listItems = books.Select(book => new SelectListItem {
                            Value = Convert.ToString(book.Id),
                            Text = book.Name,
                            Selected = book.Record == part.BookPartRecord,
                        }).ToList();

                    model.AvailableBooks = new SelectList(listItems, "Value", "Text", model.SelectedBookId);

                    return shapeHelper.EditorTemplate(TemplateName: "Parts/Chapters.TableOfContent", Model: model,
                                                      Prefix: Prefix);
                });
        }
   }
}